import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { User, UserManage } from "../../../../entity/user.model";
// import { Role } from "../../../../entity/role.model";
// import { UserProfile } from "../../../../entity/user-profile.model";
// import { UserFarm } from "../../../../entity/user-farm.model";
import { Command } from "../../../../shared/toolbar.service";
import { UserEditComponent } from "../user-edit/user-edit.component";
import { BladeData } from "../../../../shared/blade/blade-data";
import { Blade } from "../../../../shared/blade/blade.model";
import { DialogResult } from "../../../../shared/dialog.service";
import { UserService } from "../../../../service/user.service";
import { FarmService } from "../../../../service/farm.service";
import { Farm } from "../../../../entity/farm.model";
import { Observable } from "rxjs/Observable";
import { Role } from "../../../../entity/role.model";
import { UserProfile } from "../../../../entity/user-profile.model";
import { UserFarm } from "../../../../entity/user-farm.model";
import { RoleService } from "../../../../service/role.service";

import { AlarmBasicConfigListComponent } from "../../alarm-basic-config/alarm-basic-config-list/alarm-basic-config-list.component";
import { UserfarmAlarmconfigListComponent } from "../../user-farm-alarmconfig/userfarm-alarmconfig-list/userfarm-alarmconfig-list.component";
import { Company } from "../../../../entity/company.model";


@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css']
})
export class UserListComponent extends BladeContainerBase<User> {

  localhostPath: string;

  /**
   * 获取到的数据
   * 
   * @type {UserManage[]}
   * @memberof UserListComponent
   */
  userManage: UserManage[] = [];


  /**
   * 用户列表
   * 
   * @type {User[]}
   * @memberof UserListComponent
   */
  users: User[] = [];
  original: User[] = [];
  sreachValue: string = "";
  isAllChecked: boolean = false;


  constructor(
    private userService: UserService,
    private farmService: FarmService,
    private roleService: RoleService,
  ) {
    super();
  }
  private curWwwPath: string;
  private pathName: string;
  private pos: number;
  ngOnInit() {
    this.commands = [
      new Command("add", "添加", "fa fa-plus", "setofkey:insert", blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command("edit", "编辑", "fa fa-edit", "setofkey:update", blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command("delete", "删除", "fa fa-trash-o", "setofkey:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade)),
      new Command("config", "报警设置", "fa fa-edit", "setofkey:config", blade => this.exeConfig(blade), blade => this.canConfig(blade)),
      new Command("farm-alarm", "风场报警", "fa fa-edit", "setofkey:farm-alarm", blade => this.exeFarmAlarm(blade), blade => this.canFarmAlarm(blade)),      
    ];
    // this.localhostPath = window.location.origin;
    // this.localhostPath = this.localhostPath == 'http://localhost:4200' ? 'http://192.168.15.109:8080' : this.localhostPath;
    this.curWwwPath = window.location.href;
    this.pathName = window.location.pathname;
    this.pos = this.curWwwPath.indexOf(this.pathName);
    this.localhostPath = this.curWwwPath.substring(0, this.pos);
    this.localhostPath = (this.localhostPath == 'http://localhost:4200')?this.localhostPath+'/assets/images':this.localhostPath+'img/';  

    super.ngOnInit();

  }


  /**
   * 初始化数据
   * 
   * @returns {(any | Observable<any> | Promise<any>)} 
   * @memberof UserListComponent
   */
  initData(): any | Observable<any> | Promise<any> {
     this.userService.getUsersByCompanyId(this.parentEntity.company.companyId)
      .then(res => {
        if(res){
          this.original = [...res];
        }
          this.onSearch(this.sreachValue);                  
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }



  /**
     * 查询过滤
     * 
     * @param {string} keyCode 
     * 
     * @memberof DicKeyListComponent
     */
  onSearch(value: string) {
    this.sreachValue = value;
    this.isAllChecked = false;
    this.original.forEach(o => o.isChecked = false);
    value = value.toLowerCase().trim();
    this.users = [];
    this.users = value == "" ? [...this.original] : [...this.original.filter(o => o.userName.toLowerCase().startsWith(value))];
    this.currentEntity = null;
    this.canExeEdit();
    this.canDelete();
  }
  /**
   * 创建用户
   * 
   * @param {Blade} blend 
   * @memberof UserListComponent
   */
  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = "userEdit";
    data.title = "创建用户";
    data.isClosingDisabled = false;
    // let createUserBlade = this.bladeService.createBlade(UserEditComponent, data, true);
    let createUserBlade = this.bladeService.createBlade(UserEditComponent, data, true, null, this.parentEntity);
    this.bladeService.showBlade(createUserBlade, this.currentBlade);
  }

  canExeAdd(blend: Blade): boolean {
    return true;
  }

  // 报警基本设置
  exeConfig(blend: Blade) {
    let data: BladeData = new BladeData();
    data.id = "alarmBasicConfigList";
    data.title = "报警设置配置项";
    data.isClosingDisabled = false;
    let createConfigBlade = this.bladeService.createBlade(AlarmBasicConfigListComponent, data, false, null, this.currentEntity);
    this.bladeService.showBlade(createConfigBlade, this.currentBlade);
  }

  canConfig(blend?: Blade) {
    return this.currentEntity != null;
  }

  // 风场报警提示
  exeFarmAlarm(blend: Blade) {
    let data: BladeData = new BladeData();
    data.id = "userfarmAlarmconfigList";
    data.title = "风场报警提示";
    data.isClosingDisabled = false;
    let createUserfarmAlarmconfigBlade = this.bladeService.createBlade(UserfarmAlarmconfigListComponent, data, false, null, this.currentEntity);
    this.bladeService.showBlade(createUserfarmAlarmconfigBlade, this.currentBlade);
  }

  canFarmAlarm(blend?: Blade) {
    return this.currentEntity != null;
  }



  /**
   * 编辑用户
   * 
   * @param {Blade} blend 
   * @memberof UserListComponent
   */
  exeEdit(blend: Blade): void {

    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = "userEdit";
      data.title = this.currentEntity.userName;

      let sysProfile = new UserProfile();
      sysProfile.userId = 1;
      sysProfile.email = "";
      sysProfile.faxNo = "";
      sysProfile.icon = "";
      sysProfile.lastupDate = "";
      sysProfile.menuId = 1;
      sysProfile.passwordAnswer = "";
      sysProfile.passwordQuestion = "";
      sysProfile.realName = "";
      sysProfile.roleId = 1;
      sysProfile.skinId = 1;
      sysProfile.telNo = "";
      sysProfile.title = "";
      let userFarms: UserFarm[] = [];

      let userManage = new UserManage(this.currentEntity, sysProfile, userFarms);
      let userEditBlade = this.bladeService.createBlade(UserEditComponent, data, false, userManage, this.parentEntity);
      this.currentBlade.bladeService.showBlade(userEditBlade, this.currentBlade);
    }
  }
  canExeEdit(blend?: Blade): boolean {
    return this.currentEntity != null && this.currentEntity.hasOwnProperty("userId");
  }


  /**
   * 删除用户
   * 
   * @param {Blade} blend 
   * @memberof UserListComponent
   */
  exeDelete(blend: Blade): void {
    let selectedUsers = this.getSelected();
    if (selectedUsers.length > 0) {
      this.dialogService
        .showConfirmationDialog("确认删除", "是否要删除选中项？")
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;
            this.userService.batchDelete(selectedUsers.map(o => o.userId))
              .then(res => {
                if (res) {
                  this.refresh(undefined);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }
  }
  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;
  }


  /**
   * 单选
   * 
   * @param {HTMLInputElement} event 
   * @param {User} user 
   * @memberof UserListComponent
   */
  onItemCheack(event: HTMLInputElement, user: User) {
    user.isChecked = event.checked;
  }


  /**
   * 全选/全不选
   * 
   * @param {HTMLInputElement} event 
   * @memberof UserListComponent
   */
  onAllCheack(event: HTMLInputElement) {
    if (this.users.length > 0) {
      for (let i = 0; i < this.users.length; i++) {
        this.users[i].isChecked = event.checked;
      }
    }
  }

  /**
   * 获得选中项
   * 
   * @returns {User[]} 
   * @memberof User
   */
  getSelected(): User[] {
    if (this.users.length > 0) {
      let filter = this.users.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }
  onSeletedChange(selectedUser: User) {
    if (this.currentBlade.childrenCanDeactivate()) {
      this.currentEntity = selectedUser;
    }
  }
}



// WEBPACK FOOTER //
// ./src/app/module/basic/user/user-list/user-list.component.ts